<template>
  <div class="floating-ad-wrapper">
    <!-- 浮动按钮（固定样式，始终显示） -->
    <transition name="fade">
      <div 
        v-if="!dialogVisible" 
        class="floating-button" 
        @click="showDialog"
      >
        <img src="@/assets/images/logo.png" alt="Logo" class="logo-image" />
        <div class="button-text">更多<br/>服务</div>
      </div>
    </transition>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      width="600px"
      :show-close="true"
      class="ad-dialog"
      @close="handleClose"
    >
      <template #header>
        <div class="dialog-header">
          <h2>业务推广</h2>
        </div>
      </template>
      
      <div class="ad-content">
        <div class="ad-left">
          <img :src="adLogoUrl" alt="Logo" class="company-logo" />
        </div>
        
        <div class="ad-right">
          <h3 class="ad-title">{{ adTitle }}</h3>
          <div class="ad-description" v-html="adContent"></div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleLearnMore">了解更多</el-button>
          <el-button @click="dialogVisible = false">稍后再说</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { getEnabledAdvertisement } from '@/api/advertisement';

const dialogVisible = ref(false);
const adData = ref(null);
const hasShownOnLogin = ref(false); // 标记是否已在登录时显示过

// 默认内容
const defaultTitle = '数海领航 - 更多专业服务';
const defaultContent = `
<p><strong>我们还提供以下专业服务，助力您的企业发展：</strong></p>
<ul style="line-height: 1.8;">
<li>全球企业名类人群包定制，</li>
<li>跨境电商解决方案</li>
<li>海外营销数据分析</li>
<li>全球供应链管理 国际商务咨询</li>
<li>高额推广返佣奖励，</li>
<li>可OEM和API合作，</li>
<li>更多定制服务请联系客服：13360926004</li>
</ul>
`;
const defaultLink = 'https://www.shuhailinghang.cn';

// 标题（优先使用后台数据）
const adTitle = computed(() => {
  return adData.value?.title || defaultTitle;
});

// 内容（优先使用后台数据）
const adContent = computed(() => {
  return adData.value?.content || defaultContent;
});

// 弹窗中的Logo URL（从后台获取）
const adLogoUrl = computed(() => {
  if (adData.value?.logoUrl) {
    // 如果是相对路径，通过jlh-backend代理访问
    if (adData.value.logoUrl.startsWith('/profile')) {
      // 直接使用相对路径，由jlh-backend的ImageProxyController代理
      return adData.value.logoUrl;
    }
    return adData.value.logoUrl;
  }
  // 默认使用本地logo
  return new URL('@/assets/images/logo.png', import.meta.url).href;
});

// 显示弹窗
const showDialog = () => {
  dialogVisible.value = true;
};

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false;
};

// 了解更多
const handleLearnMore = () => {
  const url = adData.value?.linkUrl || defaultLink;
  window.open(url, '_blank');
};

// 获取广告数据
const fetchAdData = async () => {
  try {
    const response = await getEnabledAdvertisement();
    console.log('广告API响应:', response);
    console.log('广告数据:', response.data);
    
    // axios返回的数据在response.data中
    if (response.data && response.data.code === 200 && response.data.data) {
      adData.value = response.data.data;
      console.log('广告数据加载成功:', adData.value);
    } else {
      console.warn('广告数据格式不正确或无数据:', response.data);
    }
  } catch (error) {
    console.error('获取广告数据失败:', error);
    // 即使失败也继续显示默认内容
  }
};

onMounted(async () => {
  console.log('FloatingAd组件已挂载');
  console.log('浮动按钮应该显示在右下角');
  
  // 先获取广告数据
  await fetchAdData();
  
  // 检查是否是登录后首次加载（通过sessionStorage判断）
  const hasShownThisSession = sessionStorage.getItem('adShownOnLogin');
  
  if (!hasShownThisSession && adData.value) {
    // 延迟500ms后自动弹出广告（确保页面加载完成）
    setTimeout(() => {
      dialogVisible.value = true;
      hasShownOnLogin.value = true;
      // 标记本次会话已显示过
      sessionStorage.setItem('adShownOnLogin', 'true');
      console.log('登录后自动弹出广告');
    }, 500);
  }
});
</script>

<style scoped lang="scss">
.floating-ad-wrapper {
  position: fixed;
  z-index: 9999;
}

.floating-button {
  position: fixed;
  bottom: 160px;
  right: 30px;
  width: 65px;
  height: 65px;
  background: white;
  border-radius: 50%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 8px;
  transition: all 0.3s ease;
  z-index: 9999;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  }

  .logo-image {
    width: 30px;
    height: 30px;
    object-fit: contain;
    margin-bottom: 3px;
  }

  .button-text {
    font-size: 11px;
    color: #333;
    font-weight: 400;
    text-align: center;
    line-height: 1.1;
    white-space: nowrap;
  }
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

:deep(.ad-dialog) {
  .el-dialog__header {
    padding: 20px 20px 10px;
    border-bottom: 1px solid #eee;
  }

  .el-dialog__body {
    padding: 30px 20px;
  }

  .el-dialog__footer {
    padding: 15px 20px 20px;
    border-top: 1px solid #eee;
  }
}

.dialog-header {
  h2 {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: #333;
  }
}

.ad-content {
  display: flex;
  gap: 20px;
  min-height: 200px;

  .ad-left {
    flex-shrink: 0;
    width: 140px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start;
    padding-top: 5px;

    .company-logo {
      width: 130px;
      height: 130px;
      object-fit: contain;
    }
  }

  .ad-right {
    flex: 1;
    display: flex;
    flex-direction: column;

    .ad-title {
      font-size: 22px;
      font-weight: 600;
      color: #409EFF;
      margin: 0 0 15px 0;
    }

    .ad-description {
      font-size: 16px;
      line-height: 1.7;
      color: #666;
      flex: 1;

      :deep(p) {
        margin: 0 0 12px 0;

        strong {
          color: #333;
          font-weight: 600;
          font-size: 17px;
        }
      }

      :deep(ul) {
        margin: 8px 0;
        padding-left: 20px;

        li {
          margin-bottom: 6px;
          list-style-type: disc;
        }
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 15px;

  .el-button {
    min-width: 120px;
  }
}
</style>
